package com.x.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * ClassName: JavaConfig
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.09.05 21:13
 */

@Configuration
@ComponentScan("com.x")
@PropertySource("classpath:jdbc.properties")
@EnableAspectJAutoProxy //开启AspectJ(Aop)支持
@EnableTransactionManagement //开启事务(Tx)支持
public class JavaConfig {

    @Value("${com.x.driver}")
    private String driver;
    @Value("${com.x.url}")
    private String url;
    @Value("${com.x.username}")
    private String username;
    @Value("${com.x.password}")
    private String password;


    //Druid连接池
    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        return dataSource;
    }

    //jdbcTemplate
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource){
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);

        return jdbcTemplate;
    }


    //配置事务(Transaction)
    @Bean
    public TransactionManager manager(DataSource dataSource){
        //内部进行事务的操作
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();

        //传入连接池对象
        transactionManager.setDataSource(dataSource);

        return transactionManager;
    }

}
